package com.cqeec.bootdemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqeec.bootdemo.common.R;
import com.cqeec.bootdemo.entity.Category;
import com.cqeec.bootdemo.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    //分页查询
    @GetMapping("/page")
    public R<Page<Category>> getPage( int page,int pageSize){
        Page<Category> pageIofo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        categoryService.page(pageIofo,wrapper);
        return R.success(pageIofo);
    }
    //根据类型查询菜品分类
    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
      LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
      wrapper.eq(type!=null,Category::getType,type);
      wrapper.orderByAsc(Category::getSort);
      List<Category> list=categoryService.list(wrapper);
      return R.success(list);
    }
@DeleteMapping
    public R<String> delete(Long id){
        categoryService.removeWithCategory(id);
        return R.success("删除成功");
}
    @PostMapping
    public R<String> save( @RequestBody Category category) {
        if (categoryService.exists(new LambdaQueryWrapper<Category>()
                .eq(Category::getName, category.getName()))) {
            return R.error("分类名称已存在");
        }
        categoryService.save(category);
        return R.success("新增成功");
    }
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        if (categoryService.exists(new LambdaQueryWrapper<Category>()
                .ne(Category::getId, category.getId())
                .eq(Category::getName, category.getName()))) {
            return R.error("分类名称已存在");
        }
        categoryService.updateById(category);
        return R.success("更新成功");
        }
    @GetMapping("/{id}")
    public R<Category> getById(@PathVariable Long id) {
        return R.success(categoryService.getById(id));
    }
}
